package example.other;

import org.apache.commons.io.FileUtils;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

/**
 * 这段代码会把一个名为"original.jpg"的图片按照指定的长宽（100*100）拆分成多个图片。每一个小图片的名字为"img0.jpg", "img1.jpg" , "img2.jpg" ……依次类推。
 */
public class ImageSplitter22 {

    public static void main(String[] args) {

        String pathName = "C:\\Users\\yangyang\\Desktop\\申请材料\\图片\\IMG_20230115_165050.jpg";
        String targetPath = "C:\\Users\\yangyang\\Desktop\\申请材料\\图片\\记录2";

        try {
            BufferedImage originalImg = ImageIO.read(new File(pathName));
            int width = originalImg.getWidth();
            int height = originalImg.getHeight();
            int chunkWidth = width;
            int chunkHeight = 100;
            int rows = (height + chunkHeight - 1) / chunkHeight;
            int cols = (width + chunkWidth - 1) / chunkWidth;
            int chunk = 0;
            for (int x = 1; x <= rows; x++) {
                int x2 = x * chunkWidth;
                int y2 = 1 * chunkHeight;
                int w = Math.min(chunkWidth, width - x2);
                int h = Math.min(chunkHeight, height - y2);
                BufferedImage img = originalImg.getSubimage(x2, 0, chunkWidth, chunkHeight);
                File file = FileUtils.getFile(targetPath, "img" + chunk + ".jpg");
                ImageIO.write(img, "jpg", file);
                chunk++;
            }

            System.out.println("Splitting done");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
